#!/bin/bash
# 强制重启Flask应用脚本 - 最终修复方案

echo "🔧 开始强制重启Flask应用..."
echo "目标: 确保新的SECRET_KEY被正确加载"

cd /www/wwwroot/flask-auth

echo ""
echo "📋 当前Flask进程状态:"
ps aux | grep -E "python.*run\.py|python.*app\.py|flask" | grep -v grep

echo ""
echo "🛑 强制停止所有Flask相关进程..."

# 强制杀死所有相关进程
pkill -9 -f "python.*run\.py" 2>/dev/null
pkill -9 -f "python.*app\.py" 2>/dev/null
pkill -9 -f "flask" 2>/dev/null
pkill -9 -f "gunicorn" 2>/dev/null

echo "✅ 进程停止完成"

echo ""
echo "⏳ 等待2秒确保进程完全结束..."
sleep 2

echo ""
echo "📋 确认进程已停止:"
remaining=$(ps aux | grep -E "python.*run\.py|python.*app\.py|flask" | grep -v grep)
if [ -z "$remaining" ]; then
    echo "✅ 所有Flask进程已停止"
else
    echo "⚠️ 仍有进程运行:"
    echo "$remaining"
fi

echo ""
echo "🔧 设置环境变量..."
export SECRET_KEY="aqm-jwt-secret-1749456354171-rLD9xAdYFvBlNXa8vop3Um9zJ6l9V8qDSkhBbzVwVbCsHKvOaNsWiFmi34VpNlDD"
echo "✅ SECRET_KEY环境变量已设置"

echo ""
echo "🚀 重新启动Flask应用..."

# 检查启动文件并启动
if [ -f "run.py" ]; then
    echo "使用run.py启动应用..."
    nohup python3 run.py > flask_restart.log 2>&1 &
    startup_file="run.py"
elif [ -f "app.py" ]; then
    echo "使用app.py启动应用..."
    nohup python3 app.py > flask_restart.log 2>&1 &
    startup_file="app.py"
else
    echo "❌ 未找到启动文件"
    exit 1
fi

echo "✅ Flask应用已启动 (使用 $startup_file)"

echo ""
echo "⏳ 等待5秒让应用完全启动..."
sleep 5

echo ""
echo "📋 检查应用启动状态:"
new_processes=$(ps aux | grep -E "python.*run\.py|python.*app\.py" | grep -v grep)
if [ -n "$new_processes" ]; then
    echo "✅ Flask应用正在运行:"
    echo "$new_processes"
else
    echo "❌ Flask应用未能启动，检查日志:"
    tail -10 flask_restart.log
    exit 1
fi

echo ""
echo "🧪 测试应用连通性..."

# 测试本地连接
if curl -s -o /dev/null -w "%{http_code}" "http://localhost:5000/api/auth/test" | grep -q "200"; then
    echo "✅ 本地连接测试成功"
elif curl -s -o /dev/null -w "%{http_code}" "http://localhost:5000/" | grep -q "200"; then
    echo "✅ 本地根路径连接成功"
else
    echo "⚠️ 本地连接测试失败，但应用可能仍在启动中"
fi

# 测试外部连接
echo "🌐 测试外部连接..."
if curl -s -o /dev/null -w "%{http_code}" "http://zmyzmy.xin:5000/api/auth/test" | grep -q "200"; then
    echo "✅ 外部连接测试成功"
else
    echo "⚠️ 外部连接可能需要更多时间"
fi

echo ""
echo "🎉 强制重启完成！"
echo ""
echo "📝 重要信息:"
echo "- SECRET_KEY已通过环境变量设置"
echo "- Flask应用已完全重启"
echo "- 启动日志: flask_restart.log"
echo ""
echo "🔍 下一步："
echo "1. 等待1-2分钟让应用完全启动"
echo "2. 使用前端工具测试API访问"
echo "3. 如果仍有问题，检查启动日志: tail -f flask_restart.log"

echo ""
echo "📊 快速验证命令:"
echo "curl -X POST http://localhost:5000/auth/login \\"
echo "  -H 'Content-Type: application/json' \\"
echo "  -d '{\"username\":\"admin\",\"password\":\"admin123456\"}'"
